package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"

	"laundry-service/app/client/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type MiniProgramRedirectLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

type GetRedirectUrlRequestBody struct {
	Path           string `json:"path"`
	Query          string `json:"query"`
	ExpireType     int    `json:"expire_type"`
	ExpireInterval *int64 `json:"expire_interval,omitempty"`
	ExpireTime     *int64 `json:"expire_time,omitempty"`
	EnvVersion     string `json:"env_version"`
}

func NewMiniProgramRedirectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MiniProgramRedirectLogic {
	return &MiniProgramRedirectLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MiniProgramRedirectLogic) MiniProgramRedirect() (url string, err error) {
	accessToken, err := l.svcCtx.MiniProgram.GetAuth().GetAccessToken()

	fmt.Println("accessToken", accessToken)
	
	if err != nil {
		l.Logger.Errorf("get access token failed: %v", err)
		return "", fmt.Errorf("access token is empty")
	}
	if accessToken == "" {
		l.Logger.Error("access token is empty")
		return "", fmt.Errorf("access token is empty")
	}

	ExpireInterval := int64(1)
	requestBody := GetRedirectUrlRequestBody{
		Path:           "/pages/index/index",
		Query:          "",
		ExpireType:     1,
		ExpireInterval: &ExpireInterval,
		EnvVersion:     "release",
	}

	return l.getRedirectUrl(accessToken, requestBody)
}

func (l *MiniProgramRedirectLogic) getRedirectUrl(accessToken string, RequestBody GetRedirectUrlRequestBody) (string, error) {
	bodyBytes, err := json.Marshal(RequestBody)
	if err != nil {
		return "", err
	}

	httpClient := http.DefaultClient
	redirectRequestUrl := "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + accessToken
	resp, err := httpClient.Post(redirectRequestUrl, "application/json", bytes.NewBuffer(bodyBytes))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("failed to get redirect URL, status code: %d", resp.StatusCode)
	}
	var result map[string]interface{}
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return "", err
	}

	redirectUrl, ok := result["url_link"].(string)
	if !ok {
		return "", fmt.Errorf("failed to get redirect URL from response")
	}

	return redirectUrl, nil
}
